package com.example.eat.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.eat.R;
import com.example.eat.dao.RecipeDao;
import com.example.eat.model.Recipe;
import com.squareup.picasso.Picasso;

public class AddRecipeFragment extends Fragment {
    private static final String ARG_USER_ID = "userId";
    private static final int PICK_IMAGE_REQUEST = 1;

    private int userId;
    private EditText editTextName, editTextInstructions;
    private ImageView imageViewRecipe;
    private Spinner spinnerCategory;
    private Button buttonSave;
    private RecipeDao recipeDao;
    private String selectedCategory;
    private String imagePath;
    private int recipeId = -1;

    public AddRecipeFragment() {
        // Required empty public constructor
    }

    public static AddRecipeFragment newInstance(int userId) {
        AddRecipeFragment fragment = new AddRecipeFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userId = getArguments().getInt(ARG_USER_ID);
        }
        recipeDao = new RecipeDao(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_recipe, container, false);

        editTextName = view.findViewById(R.id.editTextName);
        editTextInstructions = view.findViewById(R.id.editTextInstructions);
        imageViewRecipe = view.findViewById(R.id.imageViewRecipe);
        spinnerCategory = view.findViewById(R.id.spinnerCategory);
        buttonSave = view.findViewById(R.id.buttonSave);

        // 设置分类下拉框
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                getContext(), R.array.recipe_categories, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);

        spinnerCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedCategory = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedCategory = getString(R.string.category_main_course);
            }
        });

        imageViewRecipe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFileChooser();
            }
        });

        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveRecipe();
            }
        });

        // 检查是否是编辑模式
        Bundle args = getArguments();
        if (args != null && args.containsKey("recipeId")) {
            recipeId = args.getInt("recipeId");
            loadRecipeData();
        }

        return view;
    }

    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK
                && data != null && data.getData() != null) {
            Uri imageUri = data.getData();
            imagePath = imageUri.toString();
            Picasso.get().load(imageUri).into(imageViewRecipe);
        }
    }

    private void loadRecipeData() {
        Recipe recipe = recipeDao.getRecipeById(recipeId);
        if (recipe != null) {
            editTextName.setText(recipe.getName());
            editTextInstructions.setText(recipe.getInstructions());
            imagePath = recipe.getImage();

            if (imagePath != null && !imagePath.isEmpty()) {
                Picasso.get().load(imagePath).into(imageViewRecipe);
            }

            // 设置分类下拉框选中项
            ArrayAdapter<CharSequence> adapter = (ArrayAdapter<CharSequence>) spinnerCategory.getAdapter();
            int position = adapter.getPosition(recipe.getCategory());
            spinnerCategory.setSelection(position);
        }
    }

    private void saveRecipe() {
        String name = editTextName.getText().toString().trim();
        String instructions = editTextInstructions.getText().toString().trim();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(instructions)) {
            Toast.makeText(getContext(), "请填写所有必填字段", Toast.LENGTH_SHORT).show();
            return;
        }

        if (recipeId != -1) {
            // 编辑现有食谱
            Recipe recipe = recipeDao.getRecipeById(recipeId);
            if (recipe == null) {
                Toast.makeText(getContext(), "食谱不存在", Toast.LENGTH_SHORT).show();
                return;
            }

            // 修改食谱属性
            recipe.setName(name);
            recipe.setInstructions(instructions);
            recipe.setCategory(selectedCategory);
            recipe.setImage(imagePath);

            // 确保不修改用户ID
            // recipe.setUserId(userId); // 不需要设置，因为从数据库加载时已经包含了userId

            // 更新食谱
            recipeDao.updateRecipe(recipe);
            Toast.makeText(getContext(), "食谱已更新", Toast.LENGTH_SHORT).show();

            // 返回前可以添加日志验证
            Recipe updatedRecipe = recipeDao.getRecipeById(recipeId);
            Log.d("RecipeUpdate", "Updated recipe user ID: " + updatedRecipe.getUserId());
        } else {
            // 新增模式
            Recipe recipe = new Recipe();
            recipe.setName(name);
            recipe.setImage(imagePath);
            recipe.setInstructions(instructions);
            recipe.setCategory(selectedCategory);
            recipe.setUserId(userId);
            long id = recipeDao.addRecipe(recipe);
            if (id != -1) {
                Toast.makeText(getContext(), "食谱已保存", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }

        getParentFragmentManager().popBackStack();
    }
}